package com.jshoperxms.controller.mall.backstage.products;

import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.mall.backstage.vo.products.ProductSkuParamsVo;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.ProductEnums;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.ProductT;
import com.jshoperxms.service.ProductTService;
import com.jshoperxms.service.impl.Serial;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by sdywcd on 16/9/23.
 * Des:
 */
@Controller
@RequestMapping("/mall/products")
public class ProductsTController extends BaseTController implements IBaseCtrl<ProductT>{

    @Resource
    private ProductTService productTService;

    private Map<String,Object>responsedata=new HashMap<>();

    /**
     *
     * @api {post} /mall/products/save 保存货物
     * @apiName 保存货物
     * @apiGroup  ProductService
     * @apiDescription 后台管理员添加货物
     * @apiVersion 0.0.1
     * @apiParam {String} psku 选择的货物sku串
     * @apiParam {String} brandid 品牌id
     * @apiParam {String} brandname 品牌名称
     * @apiParam {String} cost 成本价格
     * @apiParam {String} freezestock 预警库存
     * @apiParam
     * @apiParam {int} sort 排序
     * @apiParam {String} logo 品牌图标
     * @apiParam {String} des 品牌描述
     * @apiParam {String} status 记录状态 启用或者禁用
     *
     * @apiSuccess {String} sucflag true标记
     * @apiSuccess {String} msg  提示信息
     *
     * @apiUse operationError
     * @apiUse operationSuccess
     */

    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody ProductT rq) {
        List<ProductSkuParamsVo>paramsVos= GsonJson.parseJsonToData(rq.getPsku(),ProductSkuParamsVo.class);
        for(ProductSkuParamsVo pv:paramsVos){
            ProductT bean=new ProductT();
            bean.setProductid(this.serial.Serialid(SerialKeys.PRODUCT));
            bean.setBrandid(rq.getBrandid());
            bean.setBrandname(rq.getBrandname());
            bean.setCost(BigDecimal.valueOf(0L));
            bean.setCreatetime(DateTools.getSystemTimeBi());
            bean.setCreatorid(BaseTools.getAdminCreateId());
            bean.setFreezestock(rq.getFreezestock());
            bean.setGoodsid(StaticKey.EMPTY);
            bean.setGoodstypeid(rq.getGoodstypeid());
            bean.setGoodstypename(rq.getGoodstypename());
            bean.setHtmlpath(StaticKey.EMPTY);
            Map<String,String>map=BaseTools.parseImg(rq.getMainimg());
            bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
            bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
            List<ImgFileBean>imgs=GsonJson.parseJsonToData(rq.getImgs(),ImgFileBean.class);
            List<String>imgsstr=new ArrayList<>();
            List<String>simgsstr=new ArrayList<>();
            for(ImgFileBean img:imgs){
                imgsstr.add(img.getNormalfilepath());
                simgsstr.add(img.getCompressfilepath());
            }
            bean.setImgs(StringUtils.join(imgsstr,TagWords.SPLITDOT));
            bean.setSimgs(StringUtils.join(simgsstr,TagWords.SPLITDOT));
            bean.setIsdefault(ProductEnums.ProductIsDefault.DEFAULT.getState());
            bean.setLname(rq.getLname());
            bean.setLtypeid(rq.getLtypeid());
            bean.setMemberprice(pv.getMemberprice());
            bean.setMsync(rq.getMsync());
            bean.setNavid(rq.getNavid());
            bean.setNname(rq.getNname());
            bean.setPattrs(rq.getPattrs());
            bean.setPoints(rq.getPoints());
            bean.setPparams(rq.getPparams());
            bean.setPrice(BigDecimal.valueOf(0L));
            bean.setProductname(rq.getProductname());
            bean.setPsku(GsonJson.parseDataToJson(pv.getSelectskus()));
            bean.setPsn(pv.getPsn());
            bean.setSaleprice(pv.getSaleprice());
            bean.setSales(rq.getSales());
            bean.setSalestatus(rq.getSalestatus());
            bean.setSname(rq.getSname());
            bean.setSort(rq.getSort());
            bean.setStock(pv.getStock());
            bean.setBatchnumber(rq.getBatchnumber());
            bean.setStoreid(StaticKey.EMPTY);
            bean.setStorename(StaticKey.EMPTY);
            bean.setStypeid(rq.getStypeid());
            bean.setTotalcomment(rq.getTotalcomment());
            bean.setTotalzan(rq.getTotalzan());
            bean.setUnit(rq.getUnit());
            bean.setWeightunit(rq.getWeightunit());
            bean.setUpdatetime(DateTools.getSystemTimeBi());
            bean.setVersiont(1);
            bean.setVsales(rq.getVsales());
            bean.setWeight(rq.getWeight());
            bean.setStatus(rq.getStatus());
            bean.setPskuvals(pv.getSkuvals());
            this.productTService.save(bean);
        }
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }

    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody ProductT rq) {
        if(StringUtils.isBlank(rq.getProductid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            ProductT bean=this.productTService.findByPK(ProductT.class,rq.getProductid());
            if(bean!=null){
                ImgFileBean ifb=new ImgFileBean();
                ifb.setNormalfilepath(bean.getMainimg());
                ifb.setCompressfilepath(bean.getSmainimg());
                ifb.setBasepath(StaticKey.EMPTY);

                List<ImgFileBean>ifbs=new LinkedList<>();
                String imgs[]=StringUtils.split(bean.getImgs(),TagWords.SPLITDOT);
                String simgs[]=StringUtils.split(bean.getSimgs(),TagWords.SPLITDOT);
                if(imgs!=null&&imgs.length>0){
                    for(int i=0;i<imgs.length;i++){
                        ImgFileBean ifbi=new ImgFileBean();
                        ifbi.setNormalfilepath(imgs[i]);
                        if(simgs.length>0){
                            ifbi.setCompressfilepath(simgs[i]);
                        }else{
                            ifbi.setCompressfilepath(StaticKey.EMPTY);
                        }

                        ifbi.setBasepath(StaticKey.EMPTY);
                        ifbs.add(ifbi);
                    }
                }
                responsedata.put(TagWords.IFB,ifb);
                responsedata.put(TagWords.IFBS,ifbs);
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody ProductT rq) {
        if(StringUtils.isBlank(rq.getProductid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getProductid(), TagWords.SPLITDOT);
            for(String s:ids){
                ProductT bean=this.productTService.findByPK(ProductT.class, s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.productTService.update(bean);
                }
            }
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody ProductT rq) {
        if(StringUtils.isBlank(rq.getProductid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            ProductT bean=this.productTService.findByPK(ProductT.class,rq.getProductid());
            if(bean!=null){
                bean.setBrandid(rq.getBrandid());
                bean.setBrandname(rq.getBrandname());
                bean.setFreezestock(rq.getFreezestock());
                bean.setGoodstypeid(rq.getGoodstypeid());
                bean.setGoodstypename(rq.getGoodstypename());
                Map<String,String>map=BaseTools.parseImg(rq.getMainimg());
                bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
                bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
                List<ImgFileBean>imgs=GsonJson.parseJsonToData(rq.getImgs(),ImgFileBean.class);
                List<String>imgsstr=new ArrayList<>();
                List<String>simgsstr=new ArrayList<>();
                for(ImgFileBean img:imgs){
                    imgsstr.add(img.getNormalfilepath());
                    simgsstr.add(img.getCompressfilepath());
                }
                bean.setImgs(StringUtils.join(imgsstr,TagWords.SPLITDOT));
                bean.setSimgs(StringUtils.join(simgsstr,TagWords.SPLITDOT));
                bean.setIsdefault(ProductEnums.ProductIsDefault.DEFAULT.getState());
                bean.setLname(rq.getLname());
                bean.setLtypeid(rq.getLtypeid());
                bean.setMemberprice(rq.getMemberprice());
                bean.setMsync(rq.getMsync());
                bean.setNavid(rq.getNavid());
                bean.setNname(rq.getNname());
                bean.setPattrs(rq.getPattrs());
                bean.setPoints(rq.getPoints());
                bean.setPparams(rq.getPparams());
                bean.setProductname(rq.getProductname());
                bean.setPsku(rq.getPsku());
                bean.setPsn(rq.getPsn());
                bean.setBatchnumber(rq.getBatchnumber());
                bean.setSaleprice(rq.getSaleprice());
                bean.setSales(rq.getSales());
                bean.setSalestatus(rq.getSalestatus());
                bean.setSname(rq.getSname());
                bean.setSort(rq.getSort());
                bean.setStock(rq.getStock());
                bean.setStypeid(rq.getStypeid());
                bean.setTotalcomment(rq.getTotalcomment());
                bean.setTotalzan(rq.getTotalzan());
                bean.setUnit(rq.getUnit());
                bean.setWeightunit(rq.getWeightunit());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                bean.setVsales(rq.getVsales());
                bean.setWeight(rq.getWeight());
                bean.setStatus(rq.getStatus());
                this.productTService.update(bean);
                responsedata.put(TagWords.SUCCESS, true);
                responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @Override
    public ResponseEntity findAll() {
        return null;
    }

    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        //检查是否有自定义搜索内容 1标示进行自定义搜索逻辑
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        //如果有自定义搜索
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion;
            Criterion criterion1= Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            Criterion criterion2=null;

            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion2=Restrictions.like("productname",searchModel.getName(), MatchMode.ANYWHERE);
            }
            if(StringUtils.isNotBlank(search)){
                criterion2=Restrictions.like("productname",search,MatchMode.ANYWHERE);
            }
            if(criterion2!=null){
                criterion=Restrictions.and(criterion1).add(criterion2);
                int records=this.productTService.count(ProductT.class,criterion).intValue();
                searchModel.setRecordsTotal(records);
                searchModel.setRecordsFiltered(records);
                responsedata.put(TagWords.RECORDSTOTAL,records);
                responsedata.put(TagWords.RECORDSFILTERED,records);
                List<ProductT> list = this.productTService.findByCriteriaByPage(
                        ProductT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                        lineSize);
                this.processPageList(list);
            }
        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion;
        Criterion criterion1=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        Criterion criterion2=Restrictions.like("productname",search,MatchMode.ANYWHERE);
        criterion=Restrictions.and(criterion1).add(criterion2);
        int records=this.productTService.count(ProductT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<ProductT> list = this.productTService.findByCriteriaByPage(
                ProductT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.productTService.count(ProductT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order=BaseTools.orderByParam("productname",ordervalue,ordertype);
        List<ProductT> list = this.productTService.findByCriteriaByPage(
                ProductT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void processPageList(List<ProductT> list) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for(Iterator<ProductT> it = list.iterator(); it.hasNext();){
            ProductT bean=it.next();
            //如果缩略图没有就使用原图
            if(StringUtils.isBlank(bean.getSmainimg())){
                bean.setSmainimg(bean.getMainimg());
            }
            Map<String,Object>cellMap=new HashMap<String, Object>();
            cellMap.put("id", bean.getProductid());
            cellMap.put("smainimg",bean.getSmainimg());
            cellMap.put("psn", bean.getPsn());
            cellMap.put("productname", bean.getProductname());
            cellMap.put("nname", bean.getNname()+TagWords.HR+bean.getLname()+TagWords.HR+bean.getSname());
            cellMap.put("goodstypename", bean.getGoodstypename());
            cellMap.put("points",bean.getPoints());
            cellMap.put("saleprice", bean.getSaleprice());
            cellMap.put("memberprice", bean.getMemberprice());
            cellMap.put("weight", bean.getWeight()+ProductEnums.ProductWeightUnit.getName(bean.getWeightunit())+"/"+ProductEnums.ProductUnit.getName(bean.getUnit()));
            cellMap.put("salestatus", BaseEnums.GoodsSaleState.getName(bean.getSalestatus()));
            cellMap.put("isdefault", ProductEnums.ProductIsDefault.getName(bean.getIsdefault()));
            cellMap.put("msync", BaseEnums.MSYNC.getName(bean.getMsync()));
            cellMap.put("goodsid", bean.getGoodsid());
            cellMap.put("sort", bean.getSort());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA, data);

    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }


    @RequestMapping(value="/findProductByPage",method= RequestMethod.POST)
    public ResponseEntity findProductByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        //检查是否有自定义搜索内容 1标示进行自定义搜索逻辑
        findProductCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    public void findProductCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        //如果有自定义搜索
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();

            Criterion criterion=Restrictions.and(Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState()));

            if(StringUtils.isNotBlank(searchModel.getGoodstypeid())){
                criterion=Restrictions.and(criterion).add(Restrictions.eq("goodstypeid",searchModel.getGoodstypeid()));
            }
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("productname",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if (StringUtils.isNotBlank(searchModel.getPsn())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("psn",searchModel.getPsn(),MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("productname",search,MatchMode.ANYWHERE));
            }
            int records=this.productTService.count(ProductT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<ProductT> list = this.productTService.findByCriteriaByPage(
                    ProductT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processProductPageList(list);
        }else{
            if(StringUtils.isNotBlank(search)){
                filterProductSearch(searchModel,search);
            }else{
                findProductDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }

    public void filterProductSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        if(StringUtils.isNotBlank(searchModel.getGoodstypeid())){
            criterion=Restrictions.and(criterion).add(Restrictions.eq("goodstypeid",searchModel.getGoodstypeid()));
        }
        if(StringUtils.isNotBlank(search)){
            criterion=Restrictions.and(criterion).add(Restrictions.like("productname",search,MatchMode.ANYWHERE));
        }
        int records=this.productTService.count(ProductT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<ProductT> list = this.productTService.findByCriteriaByPage(
                ProductT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processProductPageList(list);
    }


    public void findProductDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.productTService.count(ProductT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order=BaseTools.orderByParam("productname",ordervalue,ordertype);
        List<ProductT> list = this.productTService.findByCriteriaByPage(
                ProductT.class, criterion,order, currentPage,
                lineSize);
        this.processProductPageList(list);
    }

    public void processProductPageList(List<ProductT> list) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for(Iterator<ProductT> it = list.iterator(); it.hasNext();){
            ProductT bean=it.next();
            //如果缩略图没有就使用原图
            if(StringUtils.isBlank(bean.getSmainimg())){
                bean.setSmainimg(bean.getMainimg());
            }
            Map<String,Object>cellMap=new HashMap<String, Object>();
            cellMap.put("id", bean.getProductid());
            cellMap.put("goodsid",bean.getGoodsid());
            cellMap.put("mainimg",bean.getMainimg());
            cellMap.put("psn", bean.getPsn());
            cellMap.put("productname", bean.getProductname());
            cellMap.put("brandname",bean.getBrandname());
            cellMap.put("nname", bean.getNname()+TagWords.HR+bean.getLname()+TagWords.HR+bean.getSname());
            cellMap.put("goodstypename", bean.getGoodstypename());
            cellMap.put("stock", bean.getStock());
            cellMap.put("saleprice", bean.getSaleprice());
            cellMap.put("memberprice", bean.getMemberprice());
            cellMap.put("salestatus", BaseEnums.GoodsSaleState.getName(bean.getSalestatus()));
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA, data);

    }
}
